<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/config/param.php';
require_once 'phpmailer/class.phpmailer.php';
require_once 'simpleImage.php';

class GeneralFunctions {
	public static function ubiMail($to, $subject, $message) {
		global $ubi;
		//using PHPMailer to send email through smtp server
		$mail = new PHPMailer();
		
		//get account username of admin email
//		$acc = explode("@", $ubi['SERVER']['ADMIN_EMAIL']);
						
		$mail->IsSMTP();
		$mail->Host = $ubi['SERVER']['HOST_MAIL'];
		$mail->Port = $ubi['SERVER']['HOST_MAIL_PORT'];
		$mail->SMTPAuth = true;
		
		$mail->Username = $ubi['SERVER']['ADMIN_USERNAME_EMAIL'];
		$mail->Password = $ubi['SERVER']['ADMIN_EMAIL_PASS'];
		$mail->From = $ubi['SERVER']['ADMIN_EMAIL'];
		$mail->FromName = $ubi['SERVER']['SITE_NAME'];
		$mail->Subject = $subject;
		$mail->Body = $message;
		$mail->AddAddress($to);
		$mail->IsHTML(true);
		$mail->CharSet = 'UTF-8';
		return $mail->Send();
	}
	
	/*
	 * check to see if the user logged in or not
	 * returns true if the user logged in
	 * returns false if user not logged in
	 */
	public static function isLoggedIn()	{
		//check for cookie first
		if (isset($_COOKIE['userid']) && isset($_COOKIE['username']) && isset($_COOKIE['email'])) { 
			//there is cookie about log in information		
			//set the session
			$_SESSION['userid'] = $_COOKIE['userid'];
			$_SESSION['username'] = $_COOKIE['username'];
			$_SESSION['email'] = $_COOKIE['email'];
			$_SESSION['roleid'] = $_COOKIE['roleid'];
			$_SESSION['rem'] = $_COOKIE['rem'];
			
			return true;
		} else {
			//there is no cookie about the user logged in
			//check for the session
			if (isset($_SESSION['userid']) && isset($_SESSION['username']) && isset($_SESSION['email'])) {
				//session exists
				//check to see the remember me function set on?
				if ($_SESSION['rem']) {				
					//set the cookie to the values of SESSION
					setcookie('userid', $_SESSION['userid']);
					setcookie('username', $_SESSION['username']);
					setcookie('email', $_SESSION['email']);
					setcookie('roleid', $_SESSION['roleid']);
					setcookie('rem', $_SESSION['rem']);
				}
				
				return true;
			} else {
				//no cookie, no session
				return false;
			}
		}
	}
	
	//get a date from mysql query and format it to php timestamp
	//return timestamp if can format
	//return null if can format
	public static function formatDate($date) {
		//remove all the spaces
		$date = str_replace(' ', '', $date);
		
		$pattern1 = '/[0-9]{4}(-[0-9]{2}){2}/';
		$pattern2 = '/[0-9]{2}(:[0-9]{2}){2}/';
		
		if (preg_match($pattern1, $date) && preg_match($pattern2, $date)) {
			//exist date and time
			//get date
			$arr = preg_split($pattern1, $date);
			$t = $arr[1];
			
			//get time
			$arr = preg_split($pattern2, $date);
			$d = $arr[0];
			
			//split the date into pieces
			$d = explode('-', $d);
			
			//split the time into pieces
			$t = explode(':', $t);
			
			return mktime($t[0], $t[1], $t[2], $d[1], $d[2], $d[0]);
		}
		
		return null;
	}
	
	public function createToken() {
		//begin of method createToken	
		//get the unix current time
		$time = time();
		
		//declare the code variable to hold the code that will be created
		$code = "";
		
		//iterate through each character in $username
		for ($i = 0; $i < 20 - strlen($time); $i++) {
		//begin of for $i
			
			//get the random value from mt_rand
			//the value will be from 0 to 35
			$rvalue = mt_rand(0, 35);
			
			//if the value in the range of 0 to 25, we will convert it to alphabet character
			//by adding 97 to its ascii code
			//if the value is greater than 25, we will convert it to numeric character
			//by adding 22 to its ascii code
			if ($rvalue < 26){
				$code .= chr($rvalue + 97);
			} else {
				$code .= chr($rvalue + 22);
			}			
		}//end of for $i
		
		//add the unix time to the code
		$code .= $time;
		
		return $code;
	}//end of method createToken
	
	public static function stripString($str) {
		return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');		
	}
	
	public static function getFirstElement($str) {
		$pos = strpos($str, ' ');
		if ($pos === false) {
			return $str;
		} else {
			return substr($str, 0, $pos);
		}	
	}
	
	public static function getDate($str) {
		//explode it into array
		$dobArray = explode("/", $str);
		//create date of birth from array
		$date = $dobArray[2] . '-' . $dobArray[1] . '-' . $dobArray[0];
		
		return $date; 
	}
	
	public static function calculateNumberOfPages($totalNumberOfItems, $pageSize) {
		$result = $totalNumberOfItems % $pageSize;
		$numberPage = (int)($totalNumberOfItems / $pageSize);
		if ($result != 0) {
			$numberPage++;
		}
		return $numberPage;
	}
	
	/**
	 * 
	 * This function is used to create Activation Code according to current time 
	 * @param $username username of the user that we want to create activation code for
	 */
	public static function createRandomCode() {
		//begin of method createActivationCode		
		//get the unix current time
		$time = time();
		
		//declare the code variable to hold the code that will be created
		$code = "";
		
		//iterate through each character in $username
		for ($i = 0; $i < 20 - strlen($time); $i++) {
		//begin of for $i
			
			//get the random value from mt_rand
			//the value will be from 0 to 35
			$rvalue = mt_rand(0, 35);
			
			//if the value in the range of 0 to 25, we will convert it to alphabet character
			//by adding 97 to its ascii code
			//if the value is greater than 25, we will convert it to numeric character
			//by adding 22 to its ascii code
			if ($rvalue < 26){
				$code .= chr($rvalue + 97);
			} else {
				$code .= chr($rvalue + 22);
			}			
		}//end of for $i
		
		//add the unix time to the code
		$code .= $time;
		
		return $code;
	}//end of method createActivationCode
	
	public static function get_file($file, $newfilename, $timeOut = 30) {
		$out = fopen($newfilename, 'wb');
		if ($out == FALSE){
			print "File not opened<br>";
			exit;
		}
		 
		$ch = curl_init();
		
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeOUt);
		curl_setopt($ch, CURLOPT_FILE, $out);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL, $file);
		 
		curl_exec($ch);
		 
		curl_close($ch);
	} 
	
	public static function resizeImageResource($resourceName) {
		global $ubi;
		if (!file_exists($ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['THUMBNAIL_PATH'] . '/' .$resourceName)) {
			if (file_exists($ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $resourceName)) {
				$image = new SimpleImage();
				$image->load($ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $resourceName);
				$image->resizeToWidth($ubi['SITE']['WIDTH_THUMBNAIL']);
				$image->save($ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['THUMBNAIL_PATH'] . '/' . $resourceName);
			}
		}
	}
}
?>